<?php

/**
 * Aceita valores dia/mês/ano hora:min, por exemplo 12/1/1999 12:30.
 * 
 * A função splitDHM pega uma string com o formato acima e retorna um array com seus 5 componentes, como inteiros.
 */
class FormFieldDateHourMinute extends FormFieldType {
  
  private $nowOn;
  
  public function __construct($nowOn = false) {
    $this->inputSize = 20;
    $this->htmlClass = "datehourminField";
    $this->htmlId = null;
    $this->nowOn = $nowOn;
  }
  
  public function clearHtmlClass() {
    $this->htmlClass = "datehourminField";
  }

  public function getHtml($name, $value) {
    return $this->commonHtml($name, $value);
  }

  public function validate($input) {
    return FormFieldDateHourMinute::validatevalidateDateHourMinute($input, $this->nowOn);
  }
  
  public static function validatevalidateDateHourMinute($input, $nowOn = false) {
    $pieces = explode(" ", $input);
    $dateValidate = FormFieldDate::validateDate($pieces[0], $nowOn);
    if($dateValidate !== true) {
      return $dateValidate;
    }
    if(preg_match("%^[0-9]{1,2}:[0-9]{1,2}$%", $pieces[1]) === 1) {
      $time = explode(":", $pieces[1]);
      $hour = intval($time[0]);
      $minute = intval($time[1]);
      if($hour > 23 || $hour < 0) {
        return "Hora est&aacute; fora do intevalo 0..23: <span class='userInput'>${hour}</span>.";
      }
      else if($minute < 0 || $minute > 59) {
        return "Minuto est&aacute; fora do intevalo 0..59: <span class='userInput'>${minute}</span>.";
      }
      else if($nowOn) {
        $now = new DateTime("now");
        $diff = $now->diff(FormFieldDateHourMinute::toDateTime($input));
        if($diff->invert === 1) {
          return "Data deve vir depois da data de agora.";
        }
      }
      return true;
    }
    else {
      return "Formato inv&aacute;lido para a data/hora. Deve ser dd/mm/aaaa hh:mm.";
    }
  }
  
  /**
   * Retorna um array com (dia, mes, ano, hora, minuto).
   * @param type $dhm
   */
  public static function splitDHM($dhm) {
    $pieces = explode(" ", $dhm);
    $datePieces = explode("/", $pieces[0]);
    $hmPieces = explode(":", $pieces[1]);
    return array(intval($datePieces[0]), intval($datePieces[1]),
        intval($datePieces[2]), intval($hmPieces[0]), intval($hmPieces[1]));
  }
  
  /**
   * Retorna um DateTime a partir do $dhm.
   */
  public static function toDateTime($dhm) {
    $pieces = FormFieldDateHourMinute::splitDHM($dhm);
    $year = $pieces[2];
    $month = $pieces[1];
    $day = $pieces[0];
    $hour = $pieces[3];
    $min = $pieces[4];
    $dt =  new DateTime("${year}-${month}-${day}T${hour}:${min}:0", new DateTimeZone("America/Sao_Paulo"));
    return $dt;
  }
  
}

